package com.labelimage.controller;

import cn.hutool.core.bean.BeanUtil;
import com.labelimage.bean.entity.LabelEntity;
import com.labelimage.bean.entity.TemplateEntity;
import com.labelimage.bean.param.TemplateParam;
import com.labelimage.bean.vo.DistributedVo;
import com.labelimage.bean.vo.LabelVo;
import com.labelimage.bean.vo.TemplateVo;
import com.labelimage.common.response.Result;
import com.labelimage.service.LabelService;
import com.labelimage.service.TemplateService;
import com.labelimage.task.AsyncTaskService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("template")
@Validated
public class TemplateController {
    @Resource
    private TemplateService templateService;
    @Resource
    private LabelService labelService;
    @Resource
    private AsyncTaskService asyncTaskService;

    @GetMapping("/{datasetId}")
    public Result<List<TemplateVo>> get(@PathVariable("datasetId") Long datasetId) {
        return Result.OK(templateService.lambdaQuery()
                .eq(TemplateEntity::getDatasetId, datasetId)
                .list()
                .stream()
                .map(templateEntity -> {
                    TemplateVo templateVo = TemplateVo.builder().build();
                    BeanUtil.copyProperties(templateEntity, templateVo);
                    templateVo.setLabelList(labelService.lambdaQuery()
                            .eq(LabelEntity::getTemplateId, templateEntity.getId())
                            .list()
                            .stream()
                            .map(labelEntity -> {
                                LabelVo labelVo = LabelVo.builder().build();
                                BeanUtil.copyProperties(labelEntity, labelVo);
                                return labelVo;
                            })
                            .collect(Collectors.toList()));
                    return templateVo;
                })
                .collect(Collectors.toList()));
    }


    @PostMapping("")
    public Result<String> create(@RequestBody TemplateParam templateParam) throws IOException {
        asyncTaskService.createTemplate(templateParam);
        return Result.OK();
    }

    @DeleteMapping("/{templateId}")
    public Result<String> delete(@PathVariable("templateId")Long templateId) throws IOException {
        asyncTaskService.deleteTemplate(templateId);
        return Result.OK();
    }

    @GetMapping("/distributed/{templateId}")
    public Result<List<DistributedVo>> getDistributed(@PathVariable("templateId") Long templateId) {
        return Result.OK(templateService.getDistributed(templateId));
    }

}
